#pragma once
#include <iostream>
#include <string>
#include <unistd.h>
#include "log.hpp"
#include "Init.hpp"

extern Log lg;
Init init;

class Task
{
public:
    Task()
    {}
    Task(int sockfd, const std::string& client_ip, const u_int16_t& client_port)
        : sockfd_(sockfd), client_ip_(client_ip), client_port_(client_port)
    {}

    void run()
    {
        char buffer[4096];
        ssize_t n = read(sockfd_, buffer, sizeof(buffer));
        if(n > 0)
        {
            buffer[n] = 0;
            lg(Info, "client[%s:%d] key@ %s", client_ip_.c_str(), client_port_, buffer);
            std::string echo_string = init.Translate(buffer);

            n = write(sockfd_, echo_string.c_str(), echo_string.size());
            if(n < 0)
            {
                lg(Warning, "write error: %d, errstring: %s", errno, strerror(errno));
            }
        }
        else if(n == 0)
        {
            lg(Info, "client[%s:%d] quit, sockfd: %d", client_ip_.c_str(), client_port_, sockfd_);
        }
        else
        {
            lg(Warning, "read error: %d, errstring: %s", errno, strerror(errno));
        }
        close(sockfd_);
    }     

    void operator()()
    {
        run();
    }

    ~Task(){}

private:
    int sockfd_;
    std::string client_ip_;
    u_int16_t client_port_;
};

